import mqtt from 'mqtt'
import { mapGetters } from "vuex";

export const topicsList = {
  ship: {
    // 头部的报警
    alarm: () => {
      return {
        topic: "/alarm/data",
        fn: "getAlarm",
      }
    },
    // 主机报警
    mainAlerts: () => {
      return {
        topic: "/MainPropulsion/mainPropulsionAlerts/#",
        fn: "getMainAlarm",
      }
    },
    // 发电机报警
    DGAlarm: () => {
      return {
        topic: "/GeneratorInfo/generatorAlerts/#",
        fn: "getDGAlarm",
      }
    },
    // 侧推报警
    TGAlarm: () => {
      return {
        topic: "/SideThrusterGenerator/sideThrusterGeneratorAlerts/#",
        fn: "getTGAlarm",
      }
    },
    // 主机信息
    mainInfo: () => {
      return {
        topic: "/MainPropulsion/mainPropulsionInfo/#",
        fn: "getMainInfo",
      }
    },
    // 燃油舱信息
    oilInfo: () => {
      return {
        topic: "/fuelTank/data",
        fn: "getOilInfo",
      }
    },
    // 发电机信息
    DGInfo: () => {
      return {
        topic: "/GeneratorInfo/generatorInfo/#",
        fn: "getGenerator",
      }
    },
    // 侧推信息
    TGInfo: () => {
      return {
        topic: "/SideThrusterGenerator/sideThrusterGeneratorInfo/#",
        fn: "getSideGeneratorInfo",
      }
    },
    // 定位 lon lat cog sog
    gps: () => {
      return {
        topic: "/GPS/RMC/GPS1",
        fn: "refreshShipInfo",
      }
    },
    // 罗经 - 艏向 hod
    HDT: () => {
      return {
        topic: "/GYRO/HDT/GYRO1",
        fn: "refreshShipInfo",
      }
    },
    // 罗经 - 转向速率 rot
    ROT: () => {
      return {
        topic: "/GYRO/ROT/GYRO1",
        fn: "refreshShipInfo",
      }
    },
    // 计程仪 stw
    LOG: () => {
      return {
        topic: "/LOG/VBW/LOG1",
        fn: "refreshShipInfo",
      }
    },
    // 风速风向 speed direction
    WIND: () => {
      return {
        topic: "/WIND/MWV/WIND1",
        fn: "refreshShipInfo",
      }
    },
    // 测深仪 depth
    ECHO: () => {
      return {
        topic: "/ECHO/DPT/ECHO1",
        fn: "refreshDepth",
      }
    },
    // 倾角传感器 xAxisAngle yAxisAngle
    Tilt: () => {
      return {
        topic: "/TiltSensor/tiltSensor",
        fn: "refreshShipInfo",
      }
    },
    mock: () => {
      return {
        topic: "/#",
        fn: "asd",
      }
    },
  },
  shore: {
    alarm: () => {
      return {
        topic: "/alarm/data",
        fn: "getAlarm",
      }
    }
  }
}

export default {
  data() {
    return {
      connection: {
        host: "",
        port: 8083,
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
      },
      client: {
        connected: false,
      },
    }
  },
  computed: {
    ...mapGetters(["sysType", "mmsi"]),
    topicEvent() {
      let obj = {}
      for (let item of this.topicList) {
        obj[item.topic] = item.fn
      }
      return obj
    }
  },
  methods: {
    getTopic(list) {
      const topics = topicsList[this.sysType]
      return list.map(m => topics[m](this.mmsi))
    },
    Uint8ArrayToString(fileData) {
      var dataString = "";
      for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
      }
      return dataString
    },
    // 创建连接
    createConnection() {
      const { host, port, ...options } = this.connection
      const connectUrl = `mqtt://${host}:${port}/mqtt`
      try {
        this.client = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
      this.client.on('error', error => {
        console.log('Connection failed', error)
      })
    },
    // 解析通配符
    matchesPattern(pattern, topic) {
      // Implement logic to check if the topic matches the pattern
      const regex = new RegExp('^' + pattern.replace(/\+/g, '[^/]+').replace(/#/g, '.+') + '$');
      return regex.test(topic);
    },
    // 订阅
    mqttSubscribe(topicList) {
      topicList.forEach(({ topic, fn }) => {
        this.client.subscribe(topic, (err) => {
          if (!err) {
            console.log("订阅成功: ", topic);
          }
        });
        this.client.on('message', (receivedTopic, message) => {
          if (this.matchesPattern(topic, receivedTopic)) {
            const row = JSON.parse(this.Uint8ArrayToString(message))
            this[fn](row, receivedTopic)
          }
        });
      });
    }
  },
  created() {
    const host = window.location.hostname
    // const host = "47.99.80.195"
    // const host = "10.11.12.238"
    this.connection.host = host;
    this.createConnection()
  },
  destroyed() {
    this.client.end()
  }
}
